package br.org.blacklist.core.jdo;

import br.org.blacklist.core.jdo.repository.IBlacklistRepository;

import com.google.inject.Provider;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

/**
 * This base class implements the full Repository interface for managing persistent JDO entities.
 * 
 * @param <T>
 *            the persistent entity type
 */
public abstract class BlacklistRepository<T> implements IBlacklistRepository<T> {

    private final Class<T> clazz;

    private final Provider<PersistenceManager> provider;

    protected BlacklistRepository(Class<T> clazz, Provider<PersistenceManager> pmProvider) {
        this.clazz = clazz;
        this.provider = pmProvider;
    }

    protected Query getQuery() {
        return provider.get().newQuery(clazz);
    }

    public T get(Object key) {
        PersistenceManager pm = provider.get();
        try {
            return pm.getObjectById(clazz, key);
        } catch (JDOObjectNotFoundException e) {
            return null;
        }
    }

    public void persist(T entity) {
        provider.get().makePersistent(entity);
    }

    public void delete(T entity) {
        provider.get().deletePersistent(entity);
    }

    public void runInTransaction(Runnable block) {
        Transaction tx = provider.get().currentTransaction();
        try {
            tx.begin();
            block.run();
            tx.commit();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
        }
    }
}
